package net.yunxinyong.sign.service.impl;

import net.yunxinyong.sign.aop.CECException;
import net.yunxinyong.sign.entity.*;
import net.yunxinyong.sign.mapper.*;
import net.yunxinyong.sign.service.RecordService;
import net.yunxinyong.sign.service.RegisterStatusService;
import net.yunxinyong.sign.utils.ListUtils;
import net.yunxinyong.sign.vo.RegisterStatusVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class RegisterStatusServiceImpl implements RegisterStatusService {
    @Autowired
    private RegisterStatusMapper registerStatusMapper;
    @Autowired
    private SignAdminMapper signAdminMapper;
    @Autowired
    private EcnomicInventoryMapper ecnomicInventoryMapper;
    @Autowired
    private RecordService recordService;
    @Autowired
    private StatusMapper statusMapper;
    @Autowired
    private CecBaseMapper cecBaseMapper;
    @Autowired
    private CecOneMapper cecOneMapper;
    @Autowired
    private CecTwoMapper cecTwoMapper;
    @Autowired
    private CecThreeMapper cecThreeMapper;
    @Autowired
    private CecFourMapper cecFourMapper;
    @Autowired
    private CecFiveMapper cecFiveMapper;
    @Autowired
    private CecSixMapper cecSixMapper;
    @Autowired
    private CecSevenMapper cecSevenMapper;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = CECException.class)
    public boolean insert(RegisterStatus registerStatus,Integer id) {
        //判断是否为同一个区域
        //查询企业所属区域
        String address02 = ecnomicInventoryMapper.selectByPrimaryKey((long) registerStatus.getInvId()).getReferenceAddress02();
        String area = signAdminMapper.selectByPrimaryKey(id).getArea();
        if(signAdminMapper.selectByPrimaryKey(id).getRole().equals("root") || address02.equals(area)){
            registerStatus.setCreateTime(new Date());
            registerStatus.setUpdateTime(new Date());
            boolean b = registerStatusMapper.insertSelective(registerStatus) > 0;

            //添加操作记录
            boolean insert = recordService.insert(id, registerStatus.getInvId(), null, 1);
            if (!b || !insert){
                throw new CECException(505,"操作失败");
            }
            return true;
        }else {
            throw new CECException(505,"没有操作权限");
        }

    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = CECException.class)
    public boolean update(RegisterStatus registerStatus,Integer id) {
        Integer invId = registerStatusMapper.selectByPrimaryKey(registerStatus.getId()).getInvId();
        //判断是否为同一个区域
        //查询企业所属区域
        String address02 = ecnomicInventoryMapper.selectByPrimaryKey((long) invId).getReferenceAddress02();
        String area = signAdminMapper.selectByPrimaryKey(id).getArea();
        if(signAdminMapper.selectByPrimaryKey(id).getRole().equals("root") || address02.equals(area)){
            registerStatus.setUpdateTime(new Date());
            boolean b = registerStatusMapper.updateByPrimaryKeySelective(registerStatus) > 0;
            //添加操作记录
            boolean insert = recordService.insert(id, registerStatus.getInvId(), null, 1);
            if (!b || !insert){
                throw new CECException(505,"操作失败");
            }
            //如果为已录入状态，则修改企业为不能修改
            if (registerStatus.getValueId() == 19){
                notChange(invId);
            }else if (registerStatus.getValueId() == 18){//如果为已录入状态，则修改企业为不能修改
                updadeDownloadStatus(invId);
            }
            return true;
        }else {
            throw new CECException(505,"没有操作权限");
        }
    }



    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = CECException.class)
    public List<RegisterStatusVo> getRegisterStatusList(Integer invId) {
        ArrayList<RegisterStatusVo> registerStatusVoList = new ArrayList<>();
        RegisterStatusExample registerStatusExample = new RegisterStatusExample();
        registerStatusExample.createCriteria().andInvIdEqualTo(invId);
        List<RegisterStatus> registerStatusList = registerStatusMapper.selectByExample(registerStatusExample);
        if (ListUtils.isEmpty(registerStatusList)){
            //因为企业有7中状态所以 i = 7
            for(int i = 1; i <= 7 ; i++){
                //这里先不添加企业通知状况的数据，等下有需求可以添加上
                RegisterStatus registerStatus = insertRegisterStatus(i,invId);
                RegisterStatusVo registerStatusVo = copyBean(registerStatus);
                registerStatusVoList.add(registerStatusVo);
            }
            return registerStatusVoList;
        }
        //如果查出的registerStatusList有7条数据，说明所有的状态都存在，则直接返回 registerStatusList
        if(registerStatusList.size() == 7){
            for(RegisterStatus registerStatus :registerStatusList){
                RegisterStatusVo registerStatusVo = copyBean(registerStatus);
                registerStatusVoList.add(registerStatusVo);
            }
            return registerStatusVoList;
        }
        //取出企业存在的状态
        ArrayList<Integer> dbStatusList = new ArrayList<>();
        for (RegisterStatus registerStatus : registerStatusList){
            dbStatusList.add(registerStatus.getStatusId());
            RegisterStatusVo registerStatusVo = copyBean(registerStatus);
            registerStatusVoList.add(registerStatusVo);
        }
        //剔除存在的状态（就是含有7条数据的list，减去查出来的list），然后往数据库添加新的状态
        ArrayList<Integer> statusList = new ArrayList<>();
        statusList.add(1);
        statusList.add(2);
        statusList.add(3);
        statusList.add(4);
        statusList.add(5);
        statusList.add(6);
        statusList.add(7);
        statusList.removeAll(dbStatusList);
        for(Integer integer :statusList){
            RegisterStatus registerStatus = insertRegisterStatus(integer,invId);
            RegisterStatusVo registerStatusVo = copyBean(registerStatus);
            registerStatusVoList.add(registerStatusVo);
        }
        return registerStatusVoList;
    }




    /**
     * 在管理员修改了数据库的状态后，这个类中的文字状态也需要改变
     *
     * 这个方法是把registerStatus 的属性存到registerStatusVo中
     * @param registerStatus
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = CECException.class)
    public RegisterStatusVo copyBean(RegisterStatus registerStatus){
        //从状态表查出所有状态
        StatusExample statusExample = new StatusExample();
        List<Status> statusList = statusMapper.selectByExample(statusExample);
        Integer statusId = registerStatus.getStatusId();
        Integer valueId = registerStatus.getValueId();
        RegisterStatusVo registerStatusVo = new RegisterStatusVo();
        BeanUtils.copyProperties(registerStatus,registerStatusVo);
        for(Status status : statusList){
            if(statusId.equals(status.getId())){
                registerStatusVo.setStatusString(status.getStatusValue());
            }
            if(valueId.equals(status.getId())){
                registerStatusVo.setValueString(status.getStatusValue());
            }
        }

        return registerStatusVo;
    }

    /**
     * 这个方法是，往数据库表register_status添加默认状态数据
     *
     * 这里的默认状态是写死的，如果修改了数据库需要修改这里的状态。
     * @param status
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = CECException.class)
    public RegisterStatus insertRegisterStatus(Integer status,Integer invId){
        RegisterStatus registerStatus = new RegisterStatus();
        registerStatus.setInvId(invId);
        registerStatus.setCreateTime(new Date());
        registerStatus.setUpdateTime(new Date());
        registerStatus.setStatusId(status);
        //这里所有的value的状态默认是，未回表，或者未操作。
        switch (status){
            case 1:registerStatus.setValueId(9);
                break;
            case 2:registerStatus.setValueId(11);
                break;
            case 3:registerStatus.setValueId(13);
                break;
            case 4:registerStatus.setValueId(16);
                break;
            case 5:registerStatus.setValueId(18);
                break;
            case 6:registerStatus.setValueId(20);
                break;
            case 7:registerStatus.setValueId(22);
                break;
            default:break;
        }
        registerStatusMapper.insertSelective(registerStatus);
        return registerStatus;
    }
    /**
     * 企业上传文件进度状态更新
     * @param invId
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = CECException.class)
    public void updateUploadStatus(Integer invId) {
        RegisterStatusExample registerStatusExample = new RegisterStatusExample();
        registerStatusExample.createCriteria().andStatusIdEqualTo(4).andInvIdEqualTo(invId);
        List<RegisterStatus> registerStatusList = registerStatusMapper.selectByExample(registerStatusExample);
        if (!ListUtils.isEmpty(registerStatusList)){
            RegisterStatus registerStatus = registerStatusList.get(0);
            registerStatus.setValueId(17);
            registerStatus.setUpdateTime(new Date());
            registerStatusMapper.updateByPrimaryKeySelective(registerStatus);
        }else {
            RegisterStatus registerStatus = new RegisterStatus();
            registerStatus.setInvId(invId);
            registerStatus.setStatusId(4);
            registerStatus.setCreateTime(new Date());
            registerStatus.setUpdateTime(new Date());
            registerStatus.setValueId(14);
            registerStatusMapper.insertSelective(registerStatus);
        }
    }

    /**
     * 更新下载状态，是否可以下载，都提交后可下载
     * 更新企业填表状态
     * @param invId
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = CECException.class)
    public void updadeDownloadStatus(Integer invId) {

        if (invId == null){
            return;
        }
        EcnomicInventory ecnomicInventory = ecnomicInventoryMapper.selectByPrimaryKey((long) invId);
        if (ecnomicInventory == null){
            return;
        }
        boolean base = false;
        boolean one = true;
        boolean two = true;
        boolean three = true;
        boolean four = true;
        boolean five = true;
        boolean six = true;
        boolean seven = true;

        Integer baseId = null;
        Integer oneId = null;
        Integer twoId = null;
        Integer threeId = null;
        Integer fourId = null;
        Integer fiveId = null;
        Integer sixId = null;
        Integer sevenId = null;
        //查询所属七张表对象

        CecBaseExample cecBaseExample = new CecBaseExample();
        cecBaseExample.createCriteria().andInvIdEqualTo(invId);
        List<CecBase> cecBaseList = cecBaseMapper.selectByExample(cecBaseExample);
        if (!ListUtils.isEmpty(cecBaseList)){
            base = cecBaseList.get(0).getState() != 0;
            baseId = cecBaseList.get(0).getId();
        }

        //根据企业类型判断该计算哪些表,表赋值为false
        if (ecnomicInventory.getType() == null || ecnomicInventory.getType().equals("")){
            //判断base表是否可下载
            if (base){
                if (baseId != null){
                    cecBaseList.get(0).setState(2);
                    cecBaseMapper.updateByPrimaryKeySelective(cecBaseList.get(0));
                }
            }else {
                if (baseId != null && cecBaseList.get(0).getState() == 2){
                    cecBaseList.get(0).setState(1);
                    cecBaseMapper.updateByPrimaryKeySelective(cecBaseList.get(0));
                }
            }

            return;
        }


        String[] split = ecnomicInventory.getType().split(",");



        for (String s:split){
            if (!s.equals("")){
                if (Integer.parseInt(s) == 1){
                    one = false;
                    CecOneExample cecOneExample = new CecOneExample();
                    cecOneExample.createCriteria().andInvIdEqualTo(invId).andFormTypeEqualTo(1);
                    List<CecOne> cecOneList = cecOneMapper.selectByExample(cecOneExample);
                    if (!ListUtils.isEmpty(cecOneList)){
                        one = cecOneList.get(0).getState() != 0;
                        oneId = cecOneList.get(0).getId();
                    }
                }
                if (Integer.parseInt(s) == 2){
                    two = false;
                    CecTwoExample cecTwoExample = new CecTwoExample();
                    cecTwoExample.createCriteria().andInvIdEqualTo(invId);
                    List<CecTwo> cecTwoList = cecTwoMapper.selectByExample(cecTwoExample);
                    if (!ListUtils.isEmpty(cecTwoList)){
                        two = cecTwoList.get(0).getState() != 0;
                        twoId = cecTwoList.get(0).getId();
                    }
                }
                if (Integer.parseInt(s) == 3){
                    three = false;
                    CecThreeExample cecThreeExample = new CecThreeExample();
                    cecThreeExample.createCriteria().andInvIdEqualTo(invId);
                    List<CecThree> cecThreeList = cecThreeMapper.selectByExample(cecThreeExample);
                    if (!ListUtils.isEmpty(cecThreeList)){
                        three = cecThreeList.get(0).getState() != 0;
                        threeId = cecThreeList.get(0).getId();
                    }
                }
                if (Integer.parseInt(s) == 4){
                    four = false;
                    CecFourExample cecFourExample = new CecFourExample();
                    cecFourExample.createCriteria().andInvIdEqualTo(invId).andFormTypeEqualTo(1);
                    List<CecFour> cecFourList = cecFourMapper.selectByExample(cecFourExample);
                    if (!ListUtils.isEmpty(cecFourList)){
                        four = cecFourList.get(0).getState() != 0;
                        fourId = cecFourList.get(0).getId();
                    }
                }
                if (Integer.parseInt(s) == 5){
                    five = false;
                    CecFiveExample cecFiveExample = new CecFiveExample();
                    cecFiveExample.createCriteria().andInvIdEqualTo(invId);
                    List<CecFive> cecFiveList = cecFiveMapper.selectByExample(cecFiveExample);
                    if (!ListUtils.isEmpty(cecFiveList)){
                        five = cecFiveList.get(0).getState() != 0;
                        fiveId = cecFiveList.get(0).getId();
                    }
                }
                if (Integer.parseInt(s) == 6){
                    six = false;
                    CecSixExample cecSixExample = new CecSixExample();
                    cecSixExample.createCriteria().andInvIdEqualTo(invId);
                    List<CecSix> cecSixList = cecSixMapper.selectByExample(cecSixExample);
                    if (!ListUtils.isEmpty(cecSixList)){
                        six = cecSixList.get(0).getState() != 0;
                        sixId = cecSixList.get(0).getId();
                    }
                }
                if (Integer.parseInt(s) == 7){
                    seven = false;
                    CecSevenExample cecSevenExample = new CecSevenExample();
                    cecSevenExample.createCriteria().andInvIdEqualTo(invId);
                    List<CecSeven> cecSevenList = cecSevenMapper.selectByExample(cecSevenExample);
                    if (!ListUtils.isEmpty(cecSevenList)){
                        seven = cecSevenList.get(0).getState() != 0;
                        sevenId = cecSevenList.get(0).getId();
                    }
                }
            }

        }




        Integer valueId = 13;


        //如果都已提交，更新全部表格状态为已下载/且企业状态为已提交
        if (one && two && three && four && five && six && base && seven){

           /* if(oneId != null){
                cecOneList.get(0).setState(2);
                cecOneMapper.updateByPrimaryKeySelective(cecOneList.get(0));
            }
            if (twoId != null){
                cecTwoList.get(0).setState(2);
                cecTwoMapper.updateByPrimaryKeySelective(cecTwoList.get(0));
            }
            if (threeId != null){
                cecThreeList.get(0).setState(2);
                cecThreeMapper.updateByPrimaryKeySelective(cecThreeList.get(0));
            }
            if (fourId != null){
                cecFourList.get(0).setState(2);
                cecFourMapper.updateByPrimaryKeySelective(cecFourList.get(0));
            }
            if (fiveId != null){
                cecFiveList.get(0).setState(2);
                cecFiveMapper.updateByPrimaryKeySelective(cecFiveList.get(0));
            }
            if (sixId != null){
                cecSixList.get(0).setState(2);
                cecSixMapper.updateByPrimaryKeySelective(cecSixList.get(0));
            }*/
            if (baseId != null){
                cecBaseList.get(0).setState(2);
                cecBaseMapper.updateByPrimaryKeySelective(cecBaseList.get(0));
                valueId = 15;
            }

            /*if (sevenId != null){
                cecSevenList.get(0).setState(2);
                cecSevenMapper.updateByPrimaryKeySelective(cecSevenList.get(0));
            }*/
        }else {//状态为2的改为状态为1
            /*if(oneId != null && cecOneList.get(0).getState() == 2){
                cecOneList.get(0).setState(1);
                cecOneMapper.updateByPrimaryKeySelective(cecOneList.get(0));
            }
            if (twoId != null && cecTwoList.get(0).getState() == 2){
                cecTwoList.get(0).setState(1);
                cecTwoMapper.updateByPrimaryKeySelective(cecTwoList.get(0));
            }
            if (threeId != null && cecThreeList.get(0).getState() == 2){
                cecThreeList.get(0).setState(1);
                cecThreeMapper.updateByPrimaryKeySelective(cecThreeList.get(0));
            }
            if (fourId != null && cecFourList.get(0).getState() == 2){
                cecFourList.get(0).setState(1);
                cecFourMapper.updateByPrimaryKeySelective(cecFourList.get(0));
            }
            if (fiveId != null && cecFiveList.get(0).getState() == 2){
                cecFiveList.get(0).setState(1);
                cecFiveMapper.updateByPrimaryKeySelective(cecFiveList.get(0));
            }
            if (sixId != null && cecSixList.get(0).getState() == 2){
                cecSixList.get(0).setState(1);
                cecSixMapper.updateByPrimaryKeySelective(cecSixList.get(0));
            }*/
            if (baseId != null && cecBaseList.get(0).getState() == 2){
                cecBaseList.get(0).setState(1);
                cecBaseMapper.updateByPrimaryKeySelective(cecBaseList.get(0));
            }
            if (baseId != null){
                valueId =14;
            }
            /*if (sevenId != null && cecSevenList.get(0).getState() == 2){
                cecSevenList.get(0).setState(1);
                cecSevenMapper.updateByPrimaryKeySelective(cecSevenList.get(0));
            }*/
        }
        //查询企业填表状态信息,如果没有添加
        RegisterStatusExample registerStatusExample = new RegisterStatusExample();
        registerStatusExample.createCriteria().andInvIdEqualTo(invId).andStatusIdEqualTo(3);
        List<RegisterStatus> registerStatusList = registerStatusMapper.selectByExample(registerStatusExample);
        //添加状态记录
        if (ListUtils.isEmpty(registerStatusList)){
            RegisterStatus registerStatus = new RegisterStatus();
            registerStatus.setInvId(invId);
            registerStatus.setStatusId(3);
            registerStatus.setCreateTime(new Date());
            registerStatus.setUpdateTime(new Date());
            registerStatus.setValueId(valueId);
            int insertSelective = registerStatusMapper.insertSelective(registerStatus);
            if (insertSelective <= 0){
                throw new CECException(501,"填表状态更新失败");
            }
        }else {//修改状态记录
            RegisterStatus registerStatus = registerStatusList.get(0);
            registerStatus.setUpdateTime(new Date());
            registerStatus.setValueId(valueId);
            int update = registerStatusMapper.updateByPrimaryKeySelective(registerStatus);
            if (update <= 0){
                throw new CECException(501,"填表状态更新失败");
            }
        }
    }

    /**
     * 更新企业状态为不可修改
     * @param invId
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = CECException.class)
    public void notChange(Integer invId) {
        EcnomicInventory ecnomicInventory = ecnomicInventoryMapper.selectByPrimaryKey((long) invId);
        if (ecnomicInventory == null){
            return;
        }
        if (ecnomicInventory.getType() == null || ecnomicInventory.getType().equals("")){
            return;
        }
        String[] split = ecnomicInventory.getType().split(",");
        for (String s:split){
            if (!s.equals("")){
                if (Integer.parseInt(s) == 1){
                    CecOneExample cecOneExample = new CecOneExample();
                    cecOneExample.createCriteria().andInvIdEqualTo(invId).andFormTypeEqualTo(1);
                    List<CecOne> cecOneList = cecOneMapper.selectByExample(cecOneExample);
                    if (!ListUtils.isEmpty(cecOneList)){
                        CecOne cecOne = cecOneList.get(0);
                        cecOne.setState(-1);
                        cecOneMapper.updateByPrimaryKeySelective(cecOne);
                    }
                }
                if (Integer.parseInt(s) == 2){
                    CecTwoExample cecTwoExample = new CecTwoExample();
                    cecTwoExample.createCriteria().andInvIdEqualTo(invId);
                    List<CecTwo> cecTwoList = cecTwoMapper.selectByExample(cecTwoExample);
                    if (!ListUtils.isEmpty(cecTwoList)){
                        CecTwo cecTwo = cecTwoList.get(0);
                        cecTwo.setState(-1);
                        cecTwoMapper.updateByPrimaryKeySelective(cecTwo);
                    }
                }
                if (Integer.parseInt(s) == 3){
                    CecThreeExample cecThreeExample = new CecThreeExample();
                    cecThreeExample.createCriteria().andInvIdEqualTo(invId);
                    List<CecThree> cecThreeList = cecThreeMapper.selectByExample(cecThreeExample);
                    if (!ListUtils.isEmpty(cecThreeList)){
                        CecThree cecThree = cecThreeList.get(0);
                        cecThree.setState(-1);
                        cecThreeMapper.updateByPrimaryKeySelective(cecThree);
                    }
                }
                if (Integer.parseInt(s) == 4){

                    CecFourExample cecFourExample = new CecFourExample();
                    cecFourExample.createCriteria().andInvIdEqualTo(invId).andFormTypeEqualTo(1);
                    List<CecFour> cecFourList = cecFourMapper.selectByExample(cecFourExample);
                    if (!ListUtils.isEmpty(cecFourList)){
                        CecFour cecFour = cecFourList.get(0);
                        cecFour.setState(-1);
                        cecFourMapper.updateByPrimaryKeySelective(cecFour);
                    }
                }
                if (Integer.parseInt(s) == 5){
                    CecFiveExample cecFiveExample = new CecFiveExample();
                    cecFiveExample.createCriteria().andInvIdEqualTo(invId);
                    List<CecFive> cecFiveList = cecFiveMapper.selectByExample(cecFiveExample);
                    if (!ListUtils.isEmpty(cecFiveList)){
                        CecFive cecFive = cecFiveList.get(0);
                        cecFive.setState(-1);
                        cecFiveMapper.updateByPrimaryKeySelective(cecFive);
                    }
                }
                if (Integer.parseInt(s) == 6){
                    CecSixExample cecSixExample = new CecSixExample();
                    cecSixExample.createCriteria().andInvIdEqualTo(invId);
                    List<CecSix> cecSixList = cecSixMapper.selectByExample(cecSixExample);
                    if (!ListUtils.isEmpty(cecSixList)){
                        CecSix cecSix = cecSixList.get(0);
                        cecSix.setState(-1);
                        cecSixMapper.updateByPrimaryKeySelective(cecSix);
                    }
                }
                if (Integer.parseInt(s) == 7){
                    CecSevenExample cecSevenExample = new CecSevenExample();
                    cecSevenExample.createCriteria().andInvIdEqualTo(invId);
                    List<CecSeven> cecSevenList = cecSevenMapper.selectByExample(cecSevenExample);
                    if (!ListUtils.isEmpty(cecSevenList)){
                        CecSeven cecSeven = cecSevenList.get(0);
                        cecSeven.setState(-1);
                        cecSevenMapper.updateByPrimaryKeySelective(cecSeven);
                    }
                }
            }
        }
    }


}
